import React, {Component} from 'react';
import {Input, Form} from 'antd';
import {observer, inject} from 'mobx-react';
import { get, camelCase } from 'lodash';
const getRuleName = (bindPath) => {
    const bindPathArray = bindPath.split('.');
    if (bindPathArray.length > 2) {
        return camelCase(bindPathArray.slice(bindPathArray.length - 2).join('.'));
    }
    return camelCase(bindPath);
};

export class RenInput extends React.Component {
    constructor(props) {
        super(props);
        const { storeName, bind, ...rest } = props;
        const rulePath = `rule.${getRuleName(bind)}`;
        const valuePath = `state.${bind}`;
        this.state = {
            Component: inject(storeName)(observer((args) => {
                const store = args[storeName];
                const {
                    label, placeholder, onChange, defaultValue, ...restProps
                } = rest || {};
                const value = get(store, valuePath);
                const rule = get(store, rulePath);
                const { validateStatus, help } = rule || {};
                const render = () => (
                    <Form.Item
                        label={label}
                        hasFeedback
                        validateStatus={validateStatus}
                        help={help}
                    >
                        <Input
                            placeholder={placeholder}
                            value={value}
                            onChange={store.bindSet(bind)}
                            {...restProps}
                        />
                    </Form.Item>
                );
                return render();
            })),
        };
    }

    render() {
        const { Component } = this.state;
        return <Component />;
    }
}
